﻿/*
   Open Intel 
   Copyright © 2011 – ISC. All Rights Reserved.
*/

using System.Collections.Generic;
using ISC.MapDotNetServer.Common.Data;
using ISC.MapDotNetServer.Common.Maps;
using OI.Framework;

namespace OI.Async
{
    public class MDNDrillDownQuery : MDNFeatureQueryBase
    {
        public string ShapeFilterSerial { get; private set; }
        public List<Layer> Layers { get; private set; }
        public double BufferDist { get; private set; }


        public MDNDrillDownQuery(List<Layer> layers, string shapeFilterSerial, double bufferDist)
        {
            Layers = layers;
            ShapeFilterSerial = shapeFilterSerial;
            BufferDist = bufferDist;
        }


        protected override QueryRequest BuildQueryRequest()
        {
            return new QueryRequest
            {
                ReturnShapes = true,
                ReturnShapeBounds = false,
                MaxRows = Configuration.MaxDrillDownQueryRows,
                ReturnResultSetBounds = false,
                ShapeFilterOperation = ShapeFilterOperations.DRILL_DOWN,
                ShapeFilterSerial = ShapeFilterSerial,
                ShapeFilterCoordSys = Utility.SphericalMercatorCoordSys,
                ResultShapeCoordSys = Utility.SphericalMercatorCoordSys,
                ShapeFilterBufferDistance = BufferDist,
                ReturnTypes = true,
            };
        }


        protected override IEnumerable<Query> BuildQueries()
        {
            foreach (var layer in Layers)
            {
                string tableName = layer.ConnectionSpecification.DataTable;
                string where = layer.ConnectionSpecification.WhereClause;

                var query = new Query
                {
                    DataSourceSpecification = CreateDataSourceSpecication(tableName, Utility.SphericalMercatorCoordSys, layer.ConnectionSpecification.Type, where),
                    DataSelectionKeyword = Query.DataSelectionKeywords.All,
                };

                // here is where we specify which colums to return
                if (layer.HasDrilldownColumns())
                {
                    query.Fields.AddRange(layer.GetDrilldownColumns().Split(','));
                }
                else
                {
                    query.Fields.Add("*");
                }

                yield return query;
            }
        }

    }
}
